﻿using System;
using System.Collections.Generic;
using System.Linq;
using Dolany.UtilityTool;
using Missbot.WeiboBot.Model;

namespace Missbot.WeiboBot
{
    /// <summary>
    /// 微博内容解析器
    /// </summary>
    public class WeiboParser
    {
        private string BotName { get; }
        private long WeiboUID { get; }

        public WeiboParser(string BotName, long WeiboUID)
        {
            this.BotName = BotName;
            this.WeiboUID = WeiboUID;
        }

        public List<WeiboStatusRec> Parse(WeiboListResp resp)
        {
            if (resp == null || resp.Data.List.IsNullOrEmpty())
            {
                return default;
            }

            return resp.Data.List
                       .Where(wb => !WeiboStatusRecDA.IsExist(wb.MBlogID))
                       .Select(wb => ParseContent(wb.MBlogID))
                       .Where(wb => wb != null)
                       .ToList();
        }

        public WeiboStatusRec ParseContent(string StatusID)
        {
            var requestor = new WeiboRequestor(WeiboUID);
            var resp = requestor.GetShortText(StatusID);

            var text = resp.IsLongText ? requestor.GetLongText(StatusID)?.Data?.LongTextContent : resp.TextRaw;
            text ??= string.Empty;
            return new WeiboStatusRec
            {
                BotName = BotName,
                PubTime = DateTime.Now,
                Text = text.Replace("# ", " ").Replace("##", "#"),
                StatusID = resp.MBlogID,
                Files = resp.PicInfos?.Values.Select(pic => pic.Original.Url).ToList(),
                IsIgnored = text.Contains("http://") || resp.PicInfos != null && resp.PicInfos.Count > 4
            };
        }
    }
}